package com.wh.service.initial;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.mapper.initial.LocationMapper;
import com.wh.mapper.initial.StorehouseMapper;
import com.wh.pojo.Location;
import com.wh.pojo.Storehouse;
import com.wh.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class StorehouseServiceImpl implements StorehouseService{

    @Autowired
    private StorehouseMapper storehouseMapper;


    @Autowired
    private LocationMapper locationMapper;

    @Override
    public PageResult getStorehouseList(PageResult pageResult) {
        Page<Storehouse> storehousePage = new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
        QueryWrapper<Storehouse> queryWrapper = new QueryWrapper<>();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag,"name",pageResult.getQuery());
        storehousePage = storehouseMapper.selectPage(storehousePage,queryWrapper);
        pageResult.setTotal((long) storehousePage.getRecords().size()).setRows(storehousePage.getRecords());

        return pageResult;
    }

    @Override
    public void addStorehouse(Storehouse storehouse) {
        storehouseMapper.insert(storehouse);
    }

    @Override
    public void updataStorehouse(Storehouse storehouse) {
        storehouseMapper.updateById(storehouse);
    }

    @Override
    public void deleteStorehouse(String name) throws Exception {
        Storehouse storehouse = storehouseMapper.selectById(name);

        QueryWrapper<Location> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("storehouse",name);
        List<Location> locationList = locationMapper.selectList(queryWrapper);
        if (locationList.size() != 0) throw new Exception("出库中有货位");


        storehouseMapper.deleteById(name);
    }
}
